package main

import (
	"encoding/json"
	"fmt"
	"io"
	"net/http"
)

type Data struct {
	Name string `json:"name"`
}

// 处理GET请求: http://127.0.0.1:8005/req/get?name=root
func dealGetRequestHandler(w http.ResponseWriter, r *http.Request) {
	//获取请求参数
	query := r.URL.Query()
	if len(query["name"]) > 0 {
		//方式1:通过字典下表取值
		name := query["name"][0]
		fmt.Println("通过字典下标取值:", name)
	}
	//方式2：通过get请求取值
	name2 := query.Get("name")
	fmt.Println("通过Get方式获取:", name2)
	type data struct {
		Name2 string
	}
	d := data{
		Name2: name2,
	}
	//返回JSON数据
	json.NewEncoder(w).Encode(d)
}

// 处理POST请求: http://127.0.0.1:8005/req/post {"name": "root"}
func dealPostRequestHandler(w http.ResponseWriter, r *http.Request) {
	//获取请求数据
	bodyContent, _ := io.ReadAll(r.Body)
	strData := string(bodyContent)
	var d Data
	//gin.shouldBind
	json.Unmarshal([]byte(strData), &d)
	fmt.Printf("body content:[%s]\n", string(bodyContent))
	//返回响应内容
	json.NewEncoder(w).Encode(fmt.Sprintf("收到名字：%s", d.Name))
}

func main() {
	http.HandleFunc("/req/get", dealGetRequestHandler)
	http.HandleFunc("/req/post", dealPostRequestHandler)
	http.ListenAndServe(":8005", nil)
}
